<?php namespace PFT;
/**
 * Created by PhpStorm.
 * User: chenguangpeng
 * Date: 15-5-12
 * Time: 下午4:04
 */

class MarketingHandler {

    const URL        = "http://121.41.120.34/pft/marketing/marketing.php";
    const SHARE_PAGE = 3;//分享立减活动

    private $db;
    private $m_id;
    public function __construct($m_id)
    {
        $this->m_id = $m_id;
        $dbConf = include '/var/www/html/new/d/module/common/db.conf.php';
        include_once '/var/www/html/new/d/module/common/Db.class.php';
        \PFT\Db::Conf($dbConf['remote_1']);
        $this->db = \PFT\Db::Connect();
    }

    public function __destruct()
    {
        $this->db = null;
    }

    public function StorageCheck($m_id, $pid)
    {
        $sql_product = "SELECT left_num FROM pft_marketing_p WHERE m_id=? AND pid=? LIMIT 1";
        $stmt = $this->db->prepare($sql_product);
        $stmt->execute(array($m_id, $pid));
        return $stmt->fetchColumn(0);
    }

    public function getActivity($id=0)
    {
        $id = !$id ? $this->m_id : $id;
        $sql = <<<SQL
 SELECT id as m_id,fid,activity_name,discount,discount_type,activity_type,
 buy_limit,only_member,activity_bt,activity_et,share_page FROM pft_marketing
 WHERE id=? AND status=0 AND activity_et>? LIMIT 1
SQL;
        $stmt = $this->db->prepare($sql);
        $stmt->execute(array($id, $_SERVER['REQUEST_TIME']));
        return $stmt->fetch(\PDO::FETCH_ASSOC);
    }

    /**
     * 检测微信粉丝是否满足优惠活动
     *
     * @param array $dataMark   活动数据
     * @param int $pid   产品ID
     * @param string $openid 微信OPENID
     * @param int $buyNum 购买数
     * @return array
     */
    public function DiscountCheck($dataMark, $pid, $openid, $buyNum=0)
    {
//        $dataMark = $this->getActivity($m_id);
        //验证时间
        if (!$dataMark) {
            return array(
                'status' => 'fail',
                'msg' => '活动不存在或已过期');
        }

        //检测是否必须为会员才能参与
        if ($dataMark['only_member']==1) {

            $sql = "SELECT fid FROM uu_wx_member_pft WHERE fromusername='$openid' AND aid={$dataMark['fid']} LIMIT 1";
//            echo $sql;
//            write_logs($sql, '/var/www/html/wx/debug.txt');

            $GLOBALS['le']->query($sql);
            $row = $GLOBALS['le']->fetch_assoc();
            if (!$row['fid']) {
                return array(
                    'status' => 'fail',
                    'msg'    => '抱歉，该活动仅限会员'
                );
            }

            $sql = <<<SQL
SELECT id FROM pft_member_relationship WHERE parent_id={$dataMark['fid']}
AND son_id={$row['fid']} AND status=0 LIMIT 1
SQL;
//            write_logs($sql, '/var/www/html/wx/debug.txt');
            $GLOBALS['le']->query($sql);
            $row = $GLOBALS['le']->fetch_assoc();
            if ( !$row['id']) {
                return array(
                    'status' => 'fail',
                    'msg'    => '抱歉，该活动仅限会员参与'
                );
            }
        }

        //检测库存
        $storage = $this->StorageCheck($this->m_id, $pid);
        if (!$storage || $storage < $dataMark['buy_limit']) {
            return array(
                'status' => 'fail',
                'msg'    => '抱歉，参与活动的产品库存不足' 
            );
        }

        if ($buyNum > $dataMark['buy_limit']) {
            return array(
                'status' => 'fail',
                'msg'    => '抱歉，购买数超出活动设定数'
            );
        }
        if ($buyNum > $storage) {
            return array(
                'status' => 'fail',
                'msg'    => '抱歉，购买数超出参与活动的产品库存数'
            );
        }
        //判断粉丝是否分享过指定网页
        if ($dataMark['activity_type'] == self::SHARE_PAGE) {
            $sql = "SELECT id FROM pft_marketing_op WHERE openid='$openid' AND page_id={$dataMark['share_page']} LIMIT 1";
//            echo $sql;exit;
            $stmt = $this->db->prepare($sql);
            $stmt->execute(array($openid, $dataMark['share_page']));
            if (!$stmt->fetchColumn(0)) {
                return array(
                    'status' => 'fail',
                    'msg'    => '抱歉，您还没有分享过指定的页面无法参与此优惠活动:'.$openid,
                );
            }
        }

      $sql = <<<SQL
      SELECT count(*) FROM pft_marketing_order
      WHERE activity_id=? AND pid=? AND openid=?
SQL;
        $stmt = $this->db->prepare($sql);
        $stmt->execute(array($this->m_id, $pid, $openid));
        $buyTotal = $stmt->fetchColumn(0);

        if ($buyTotal>0 && $buyTotal >= $dataMark['buy_limit']) {
            return array(
                'status' => 'fail',
                'msg'    => '您已参与过此优惠活动'
            );
        }
        return array('status' => 'ok', 'msg' => 'ok');
    }




    public function Order($mid, $pid, $order_num, $activity_id, $openid, $tnum)
    {
        $data = array(
            'mid'           => $mid,
            'pid'           => $pid,
            'ordernum'      => $order_num,
            'activity_id'   => $activity_id,
            'openid'        => $openid,
            'created_time'  => date('Y-m-d H:i:s'),
        );
        self::CutStorage($tnum, $activity_id, $pid);
        $last_id = Db::Insert($data, 'pft_marketing_order');
        return $last_id;
    }

    /**
     * 库存减少
     *
     * @param int $num  减少数量
     * @param int $m_id 活动ID
     * @param int $pid  产品ID
     * @return bool|int
     */
    public function CutStorage($num, $m_id, $pid)
    {
        $sql_chk = "SELECT left_num FROM pft_marketing_p"
            . " WHERE m_id=$m_id AND pid=$pid LIMIT 1";
        //write_logs('left num='.$sql_chk, '/var/www/html/wx/debug.txt');
        $stmt = $this->db->prepare($sql_chk);
        $stmt->execute();
        $left_num = $stmt->fetchColumn(0);
//        write_logs('left num='.$left_num, '/var/www/html/wx/debug.txt');
        if ($left_num < $num) {
            return false;
        }
        $left_num = $left_num - $num;
        $sql_cut = "UPDATE pft_marketing_p SET left_num=$left_num"
            . " WHERE m_id=$m_id AND pid=$pid LIMIT 1";
//        write_logs($sql_cut, '/var/www/html/wx/debug.txt');
        return $this->db->exec($sql_cut);
    }
}

if (!function_exists('write_log')) {
    function write_logs($txt,$file='/var/www/html/alipay/new_log.txt'){
        $fp = fopen($file,"a");
        flock($fp, LOCK_EX);
        fwrite($fp,date("Y-m-d H:i:s").":".$txt."\n");
        flock($fp, LOCK_UN);
        fclose($fp);
    }
}